<template>
  <view class="chat-container">
    <!-- 重连提示 -->
    <view v-if="reconnecting" class="reconnect-banner">
      <text>🔄</text>
      <text>实时服务连接中，部分功能暂不可用...</text>
    </view>
    
    <!-- 聊天头部组件 -->
    <ChatHeader 
      :userName="currentChatUser.name"
      :isOnline="currentChatUser.isOnline"
      :connectionStatus="connectionStatus"
      @back="goBack"
      @call="makeCall"
      @more="showMoreOptions"
    />

    <!-- 消息列表 -->
    <scroll-view 
      class="message-list" 
      scroll-y="true" 
      :scroll-into-view="scrollToView"
      scroll-with-animation
      @scrolltoupper="loadMoreMessages"
    >
      <!-- 加载更多提示 -->
      <view v-if="loadingMore" class="loading-more">
        <text class="loading-text">加载更多消息...</text>
      </view>
      
      <!-- 消息气泡组件 -->
      <MessageBubble 
        v-for="(message, index) in visibleMessages" 
        :key="message.id || index"
        :id="`msg-${index}`"
        :message="message"
        :isMine="isMyMessage(message)"
        @preview-image="previewImage"
      />
    </scroll-view>

    <!-- 输入区域组件 -->
    <MessageInput 
      :value="inputMessage"
      @input="handleInput"
      @send="sendMessage"
      @show-emoji="showEmojiPicker"
      @choose-image="chooseImage"
      @choose-file="chooseFile"
      @show-voice="showVoiceRecord"
      @focus="scrollToBottom"
    />

    <!-- 表情选择器 -->
    <SheetModal 
      :visible="showEmojiModal" 
      title="选择表情" 
      :show-close="true"
      @close="closeEmojiModal"
    >
      <view class="emoji-grid">
        <view 
          v-for="emoji in emojis" 
          :key="emoji"
          class="emoji-item"
          @click="insertEmoji(emoji)"
        >
          {{ emoji }}
        </view>
      </view>
    </SheetModal>

    <!-- 更多选项弹窗 -->
    <SheetModal 
      :visible="showMoreOptionsModal" 
      title="更多选项" 
      :show-close="true"
      @close="closeMoreOptions"
    >
      <view class="options-list">
        <view class="option-item" @click="clearMessages">
          <text class="option-icon">🗑️</text>
          <text class="option-text">清空消息</text>
        </view>
        <view class="option-item" @click="exportMessages">
          <text class="option-icon">📤</text>
          <text class="option-text">导出聊天记录</text>
        </view>
        <view class="option-item" @click="showChatSettings">
          <text class="option-icon">⚙️</text>
          <text class="option-text">聊天设置</text>
        </view>
      </view>
    </SheetModal>
  </view>
</template>

<script>
import chatService from '../../utils/websocket-chat-service.js'
import apiService from '../../utils/api-service.js'
import appStateManager from '../../utils/app-state-manager.js'
import connectionManager from '../../utils/connection-manager.js'
import chatMessageManager from '../../utils/chat-message-manager.js'
import ChatHeader from './components/ChatHeader.vue'
import MessageBubble from './components/MessageBubble.vue'
import MessageInput from './components/MessageInput.vue'
import SheetModal from '../../components/SheetModal.vue'

export default {
  components: {
    ChatHeader,
    MessageBubble,
    MessageInput,
    SheetModal
  },
  
  data() {
    return {
      messages: [],
      inputMessage: '',
      currentChatUser: {
        id: '',
        name: '聊天用户',
        avatar: '',
        isOnline: true
      },
      roomId: '',
      scrollToView: '',  // 简化：只用一个变量控制滚动
      loadingMore: false,
      isSending: false,
      maxVisibleMessages: 50,
      serverOnline: false,
      chatConnected: false,
      reconnecting: false,
      showEmojiModal: false,
      showMoreOptionsModal: false,
      emojis: ['😀', '😃', '😄', '😁', '😆', '😅', '😂', '🤣', '😊', '😇', '🙂', '🙃', '😉', '😌', '😍', '🥰', '😘', '😗', '😙', '😚', '😋', '😛', '😝', '😜', '🤪', '🤨', '🧐', '🤓', '😎', '🤩', '🥳', '😏', '😒', '😞', '😔', '😟', '😕', '🙁', '☹️', '😣', '😖', '😫', '😩', '🥺', '😢', '😭', '😤', '😠', '😡', '🤬', '🤯', '😳', '🥵', '🥶', '😱', '😨', '😰', '😥', '😓']
    }
  },
  
  computed: {
    visibleMessages() {
      if (this.messages.length <= this.maxVisibleMessages) {
        return this.messages
      }
      return this.messages.slice(-this.maxVisibleMessages)
    },
    
    connectionStatus() {
      // 1. 检查基础连接状态
      if (!this.serverOnline) return 'disconnected'
      if (!this.chatConnected) return 'disconnected'
      if (this.reconnecting) return 'reconnecting'
      
      // 2. 检查对方是否在线（在同一个房间）
      // 注意：后端的 isOnline 已经代表"是否在同一个房间"
      // 绿色 = 双方都在聊天室（对方在线）
      // 红色 = 对方不在聊天室（对方离线）
      if (this.currentChatUser && this.currentChatUser.isOnline) {
        return 'connected'  // 🟢 绿色：对方在同一个聊天室
      } else {
        return 'disconnected'  // 🔴 红色：对方不在聊天室
      }
    }
  },
  
  async onLoad(options) {
    console.log('[Chat] 聊天页面加载，参数:', options)
    
    try {
      // 1. 验证参数
      if (!options || !options.userId) {
        console.error('[Chat] 缺少必要的用户ID参数')
        uni.showToast({ 
          title: '参数错误，无法打开聊天', 
          icon: 'none',
          duration: 2000
        })
        setTimeout(() => {
          uni.navigateBack()
        }, 2000)
        return
      }
      
      // 2. 设置聊天用户信息
      this.currentChatUser = {
        id: options.userId,
        name: options.userName || '聊天用户',
        avatar: '',
        isOnline: false  // 默认不在房间（离线）
      }
      
      console.log('[Chat] 当前聊天用户:', this.currentChatUser)
      
      // 3. 生成房间ID
      this.roomId = this.generateRoomId()
      
      // 4. 初始化状态订阅
      this.initStateSubscriptions()
      
      // 5. 订阅消息
      this.subscribeToMessages()
      
      // 6. 初始化聊天服务
      await this.initChatService()
      
      // 7. 强制刷新状态（确保状态图标正确）
      this.$nextTick(() => {
        this.forceUpdateConnectionStatus()
      })
      
      // 8. 如果已连接，加入房间并加载历史消息
      if (chatService.isConnected) {
        setTimeout(async () => {
          try {
            console.log('[Chat] 准备加入房间:', this.roomId)
            await chatService.joinRoom(this.roomId)
            console.log('[Chat] 成功加入房间')
            await this.loadHistoryMessages()
            console.log('[Chat] 历史消息加载完成')
          } catch (e) {
            console.error('[Chat] 加入房间失败:', e)
            uni.showToast({ title: '加入聊天室失败', icon: 'none' })
          }
        }, 500)
      } else {
        console.warn('[Chat] 聊天服务未连接，尝试初始化')
      }
    } catch (error) {
      console.error('[Chat] 聊天页面加载失败:', error)
      uni.showToast({
        title: '聊天加载失败: ' + (error.message || '未知错误'),
        icon: 'none',
        duration: 2000
      })
    }
  },
  
  async onShow() {
    console.log('[Chat] 页面显示，刷新房间状态')
    
    // 刷新服务器状态
      appStateManager.refreshServerStatus()
    
    // 🔧 修正：聊天页面不应该请求全局在线用户列表
    // 这会影响好友列表的全局在线状态显示
    // 聊天页面只需要关注房间内的状态即可
    console.log('[Chat] 聊天页面不请求全局在线用户，只关注房间状态')
  },
  
  async onUnload() {
    console.log('[Chat] 页面卸载，离开聊天房间')
    
    // 🔧 修复：退出聊天页面时，离开房间
    if (this.roomId && chatService.isConnected) {
      try {
        await chatService.leaveRoom(this.roomId)
        console.log('[Chat] 已离开聊天房间:', this.roomId)
      } catch (error) {
        console.error('[Chat] 离开房间失败:', error)
      }
    }
    
    // 清理消息订阅
    chatMessageManager.unsubscribe(this.roomId)
    
    // 保持WebSocket连接，不影响全局在线状态
  },
  
  methods: {
    // ========== 状态管理 ==========
    initStateSubscriptions() {
      // 1. 先刷新服务器状态
      appStateManager.refreshServerStatus()
      
      // 2. 初始化当前状态
      const serverState = appStateManager.getState('server')
      const chatState = appStateManager.getState('chat')
      
      // 3. 检查 WebSocket 实际连接状态
      const isWsConnected = chatService && chatService.isConnected
      
      this.serverOnline = serverState.isOnline
      this.chatConnected = chatState.isConnected || isWsConnected
      this.reconnecting = chatState.reconnectAttempts > 0
      
      console.log('[Chat] 初始化状态检查:')
      console.log('  - serverState.isOnline:', serverState.isOnline)
      console.log('  - chatState.isConnected:', chatState.isConnected)
      console.log('  - chatService.isConnected:', isWsConnected)
      console.log('  - 最终 serverOnline:', this.serverOnline)
      console.log('  - 最终 chatConnected:', this.chatConnected)
      console.log('  - connectionStatus computed:', this.connectionStatus)
      
      // 4. 订阅状态变化
      appStateManager.subscribe('server', (serverState) => {
        this.serverOnline = serverState.isOnline
        console.log('[Chat] 服务器状态更新:', this.serverOnline, '→ connectionStatus:', this.connectionStatus)
      })
      
      appStateManager.subscribe('chat', (chatState) => {
        this.chatConnected = chatState.isConnected
        this.reconnecting = chatState.reconnectAttempts > 0
        console.log('[Chat] 聊天连接状态更新:', this.chatConnected, '重连中:', this.reconnecting, '→ connectionStatus:', this.connectionStatus)
      })
      
      connectionManager.setWebSocketService(chatService)
      connectionManager.start()
    },
    
    subscribeToMessages() {
      console.log('[Chat] 订阅消息管理器，房间ID:', this.roomId)
      
      chatMessageManager.subscribe(this.roomId, (messages) => {
        const oldCount = this.messages.length
        const newCount = messages.length
        
        console.log('[Chat] 收到消息更新:', {
          旧数量: oldCount,
          新数量: newCount,
          是否有新消息: newCount > oldCount
        })
        
        this.messages = messages
        
        // 如果有新消息（包括自己发送和接收的），滚动到底部
        if (newCount > oldCount) {
          console.log('[Chat] 检测到新消息，准备滚动...')
          // 使用 setTimeout 确保 DOM 完全渲染后再滚动
        this.$nextTick(() => {
            setTimeout(() => {
          this.scrollToBottom()
            }, 100)
          })
        }
      })
      
      // 立即尝试加载已有消息
      const existingMessages = chatMessageManager.getMessages(this.roomId)
      if (existingMessages && existingMessages.length > 0) {
        console.log('[Chat] 发现已有消息:', existingMessages.length, '条')
        this.messages = existingMessages
        this.$nextTick(() => {
          setTimeout(() => {
            this.scrollToBottom()
          }, 100)
        })
      } else {
        console.log('[Chat] 当前没有历史消息')
      }
    },
    
    generateRoomId() {
      const currentUser = this.getCurrentUser()
      if (!currentUser || !this.currentChatUser.id) {
        return `room_${Date.now()}`
      }
      
      return chatMessageManager.generateRoomId([
        currentUser.id.toString(),
        this.currentChatUser.id.toString()
      ], 'private')
    },
    
    // ========== 消息操作 ==========
    async sendMessage() {
      if (!this.inputMessage.trim() || this.isSending) return
      
      const messageText = this.inputMessage.trim()
      this.inputMessage = ''
      this.isSending = true
      
      try {
        const currentUser = this.getCurrentUser()
        const tempMessage = {
          id: `temp_${Date.now()}`,
          content: messageText,
          type: 'text',
          sender: {
            id: currentUser.id,
            name: currentUser.name,
            avatar: currentUser.avatar
          },
          timestamp: new Date().toISOString(),
          status: 'sending'
        }
        
        this.messages.push(tempMessage)
        this.$nextTick(() => this.scrollToBottom())
        
        // 发送消息到服务器
        await chatService.sendMessage(messageText, this.roomId)
        
        tempMessage.status = 'sent'
      } catch (error) {
        console.error('发送消息失败:', error)
        uni.showToast({ title: '发送失败', icon: 'error' })
      } finally {
        this.isSending = false
      }
    },
    
    handleInput(value) {
      this.inputMessage = value
    },
    
    async loadHistoryMessages() {
      try {
        console.log('[Chat] 开始加载历史消息，房间ID:', this.roomId)
        
        // 1. 先尝试从缓存加载
        const cachedMessages = chatMessageManager.getMessages(this.roomId)
        if (cachedMessages && cachedMessages.length > 0) {
          console.log('[Chat] 从缓存加载到', cachedMessages.length, '条消息')
          this.messages = cachedMessages
          this.$nextTick(() => this.scrollToBottom())
        }
        
        // 2. 从服务器获取历史消息
        try {
          const res = await apiService.get(`/chat/messages?room_id=${encodeURIComponent(this.roomId)}`)
          
          if (res && res.code === 'SUCCESS' && Array.isArray(res.data)) {
            console.log('[Chat] 从服务器获取到', res.data.length, '条历史消息')
            // 将服务器消息保存到消息管理器
            chatMessageManager.setHistoryMessages(this.roomId, res.data)
          } else {
            console.log('[Chat] 服务器未返回历史消息')
          }
        } catch (apiError) {
          console.warn('[Chat] 从服务器加载历史消息失败:', apiError)
        }
      } catch (error) {
        console.error('[Chat] 加载历史消息失败:', error)
      }
    },
    
    async loadMoreMessages() {
      if (this.loadingMore) return
      this.loadingMore = true
      
      setTimeout(() => {
        this.loadingMore = false
      }, 1000)
    },
    
    isMyMessage(message) {
      const currentUser = this.getCurrentUser()
      return currentUser && message.sender?.id === currentUser.id
    },
    
    // ========== UI操作 ==========
    scrollToBottom() {
      this.$nextTick(() => {
        const lastIndex = this.visibleMessages.length - 1
        if (lastIndex >= 0) {
          const targetId = `msg-${lastIndex}`
          console.log('[Chat] 滚动到底部，目标消息:', targetId)
          
          // 先重置
          this.scrollToView = ''
          
          // 延迟后设置，确保触发滚动
          this.$nextTick(() => {
            this.scrollToView = targetId
            console.log('[Chat] scrollToView 已设置为:', targetId)
          })
        }
      })
    },
    
    previewImage(imageUrl) {
      uni.previewImage({
        urls: [imageUrl],
        current: imageUrl
      })
    },
    
    showEmojiPicker() {
      this.showEmojiModal = true
    },
    
    closeEmojiModal() {
      this.showEmojiModal = false
    },
    
    insertEmoji(emoji) {
      this.inputMessage += emoji
      this.closeEmojiModal()
    },
    
    chooseImage() {
      uni.chooseImage({
        count: 1,
        success: (res) => {
          console.log('选择图片:', res.tempFilePaths[0])
        }
      })
    },
    
    chooseFile() {
      uni.showToast({ title: '文件发送功能开发中', icon: 'none' })
    },
    
    showVoiceRecord() {
      uni.showToast({ title: '语音功能开发中', icon: 'none' })
    },
    
    // ========== 更多操作 ==========
    goBack() {
      uni.navigateBack()
    },
    
    makeCall() {
      uni.showToast({ title: '通话功能开发中', icon: 'none' })
    },
    
    showMoreOptions() {
      this.showMoreOptionsModal = true
    },
    
    closeMoreOptions() {
      this.showMoreOptionsModal = false
    },
    
    clearMessages() {
      uni.showModal({
        title: '清空消息',
        content: '确定要清空所有消息吗？',
        success: (res) => {
          if (res.confirm) {
            chatMessageManager.clearMessages(this.roomId)
            this.messages = []
            this.closeMoreOptions()
            uni.showToast({ title: '已清空消息', icon: 'success' })
          }
        }
      })
    },
    
    exportMessages() {
      uni.showToast({ title: '导出功能开发中', icon: 'none' })
      this.closeMoreOptions()
    },
    
    showChatSettings() {
      uni.showToast({ title: '设置功能开发中', icon: 'none' })
      this.closeMoreOptions()
    },
    
    // ========== 工具方法 ==========
    getCurrentUser() {
      try {
        const currentUser = uni.getStorageSync('currentUser')
        return currentUser ? JSON.parse(currentUser) : null
      } catch (error) {
        console.error('获取当前用户失败:', error)
        return null
      }
    },
    
    async initChatService() {
      try {
        if (!chatService.isConnected) {
          await chatService.init()
        }
        
        // 监听消息
        chatService.onMessage((message) => {
          console.log('收到WebSocket消息:', message)
          chatMessageManager.handleServerMessage(message)
          
          // 🔧 监听房间进入/离开事件，直接更新状态
          if (message.type === 'room_joined' || message.type === 'room_left') {
            const userId = message.data?.user_id || message.userId
            const roomId = message.data?.room_id || message.roomId
            
            console.log(`[Chat] 🔔 收到房间事件:`, {
              type: message.type,
              userId,
              roomId,
              currentRoomId: this.roomId,
              currentChatUserId: this.currentChatUser.id
            })
            
            // 只处理当前房间的对方事件
            if (roomId === this.roomId && userId !== parseInt(this.currentChatUser.id)) {
              const isInRoom = message.type === 'room_joined'
              
              console.log(`[Chat] ✅ 处理对方${isInRoom ? '进入' : '离开'}房间`)
              
              // 直接更新状态
              this.currentChatUser = {
                ...this.currentChatUser,
                isOnline: isInRoom
              }
              
              this.$forceUpdate()
            } else {
              console.log(`[Chat] ❌ 忽略房间事件:`, {
                reason: roomId !== this.roomId ? '不同房间' : '是自己'
              })
            }
          }
        })
        
        // 监听状态变化
        chatService.onStatusChange((statusInfo) => {
          console.log('聊天服务状态变化:', statusInfo)
          const isConnected = statusInfo.status === 'connected' || statusInfo.status === 'online_users'
          const reconnectAttempts = statusInfo.status === 'reconnecting' ? 1 : 0
          appStateManager.updateChatConnectionStatus(isConnected, reconnectAttempts)
          
          if (statusInfo.status === 'connected') {
            // 🔧 修正：聊天页面不应该请求全局在线用户列表
            // 这会影响好友列表的全局在线状态显示
            console.log('[Chat] WebSocket连接成功，不请求全局在线用户')
            
            // 🔧 关键修复：WebSocket连接成功后，立即加入房间
            if (this.roomId) {
              console.log('[Chat] WebSocket已连接，加入房间:', this.roomId)
              chatService.joinRoom(this.roomId).then(() => {
                console.log('[Chat] 成功加入房间，加载历史消息')
                this.loadHistoryMessages()
              }).catch(err => {
                console.error('[Chat] 加入房间失败:', err)
              })
            }
          }
        })
        
        // 监听在线状态变化（备用方案）
        chatService.onOnlineStatusChange((statusInfo) => {
          console.log('[Chat] 收到在线状态变化:', statusInfo)
          
          // 设置连接状态
          if (chatService && chatService.isConnected) {
            this.chatConnected = true
          }
          
          // 🔧 修正：后端没有房间事件，使用在线状态变化来推断房间状态
          const otherUserId = parseInt(this.currentChatUser.id)
          
          // 检查是否有用户新上线或新离线
          if (statusInfo.newOnline && statusInfo.newOnline.includes(otherUserId)) {
            console.log(`[Chat] 🟢 对方上线，进入房间`)
            this.currentChatUser = { ...this.currentChatUser, isOnline: true }
          } else if (statusInfo.newOffline && statusInfo.newOffline.includes(otherUserId)) {
            console.log(`[Chat] 🔴 对方离线，离开房间`)
            this.currentChatUser = { ...this.currentChatUser, isOnline: false }
          } else {
            // 没有变化，不更新状态
            console.log(`[Chat] 在线状态无变化，保持当前状态`)
          }
          
          console.log('[Chat] → serverOnline:', this.serverOnline)
          console.log('[Chat] → chatConnected:', this.chatConnected)
          console.log('[Chat] → currentChatUser.isOnline:', this.currentChatUser.isOnline)
          console.log('[Chat] → connectionStatus:', this.connectionStatus)
          
          // 强制更新视图
          this.$forceUpdate()
        })
        
        // 初始化时检查对方是否在房间
        if (chatService.isConnected) {
          const onlineUsers = chatService.getOnlineUsers()
          const otherUserId = parseInt(this.currentChatUser.id)
          const isInRoom = onlineUsers.includes(otherUserId)
          
          this.currentChatUser = {
            ...this.currentChatUser,
            isOnline: isInRoom
          }
          
          console.log(`[Chat] 初始化：${isInRoom ? '🟢' : '🔴'} 对方${isInRoom ? '在' : '不在'}房间`)
          
          console.log('[Chat] → currentChatUser.isOnline:', this.currentChatUser.isOnline)
          console.log('[Chat] → connectionStatus:', this.connectionStatus)
          
          // 强制更新视图
          this.$forceUpdate()
        }
      } catch (error) {
        console.error('初始化聊天服务失败:', error)
      }
    },
    
    cleanup() {
      connectionManager.stop()
      chatMessageManager.unsubscribe(this.roomId)
    },
    
    // ========== 状态强制刷新 ==========
    forceUpdateConnectionStatus() {
      // 强制检查并更新连接状态
      const isWsConnected = chatService && chatService.isConnected
      const serverState = appStateManager.getState('server')
      
      console.log('[Chat] 强制刷新连接状态:')
      console.log('  - chatService.isConnected:', isWsConnected)
      console.log('  - serverState.isOnline:', serverState.isOnline)
      
      if (isWsConnected && serverState.isOnline) {
        this.serverOnline = true
        this.chatConnected = true
        this.reconnecting = false
        console.log('  - 设置为已连接状态')
      }
      
      console.log('  - 最终 connectionStatus:', this.connectionStatus)
      
      // 强制触发视图更新
      this.$forceUpdate()
    }
  }
}
</script>

<style>
/* 页面级别样式 - 确保页面填满屏幕 */
page {
  height: 100%;
  background: #f5f5f5;
}
</style>

<style scoped>
.chat-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
  box-sizing: border-box;
}

.reconnect-banner {
  flex-shrink: 0;
  background: #fffbe6;
  color: #8c6d1f;
  padding: 12rpx 20rpx;
  font-size: 22rpx;
  border-bottom: 1rpx solid #f0e6cc;
  display: flex;
  align-items: center;
  gap: 12rpx;
}

.message-list {
  flex: 1;
  flex-shrink: 1;
  overflow-y: auto;
  overflow-x: hidden;
  min-height: 0;
}

.loading-more {
  text-align: center;
  padding: 20rpx;
}

.loading-text {
  font-size: 22rpx;
  color: #999;
}

/* 表情网格 */
.emoji-grid {
  display: grid;
  grid-template-columns: repeat(8, 1fr);
  gap: 16rpx;
  padding: 20rpx;
  max-height: 600rpx;
  overflow-y: auto;
}

.emoji-item {
  font-size: 48rpx;
  text-align: center;
  padding: 16rpx;
  cursor: pointer;
  transition: transform 0.2s;
}

.emoji-item:active {
  transform: scale(1.2);
}

/* 选项列表 */
.options-list {
  padding: 16rpx 0;
}

.option-item {
  display: flex;
  align-items: center;
  gap: 16rpx;
  padding: 24rpx 32rpx;
  transition: background 0.3s ease;
}

.option-item:active {
  background: #f8f9fa;
}

.option-icon {
  font-size: 32rpx;
}

.option-text {
  font-size: 26rpx;
  color: #333;
}
</style>

